package com.example.demo.netty.websocket;

import com.example.demo.netty.websocket.proto.ProtobufInfo;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 这里是要连接前端来做通讯的
 * 可以理解为一个前后端集成demo
 */
public class WSServer {
    public static void main(String[] args) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(10);

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    // 使用Http编解码器
                                    .addLast(new HttpServerCodec())
                                    // 添加ChunkedWriteHandler处理器
                                    .addLast(new ChunkedWriteHandler())
                                    // 将多次请求的数据聚合起来
                                    .addLast(new HttpObjectAggregator(8192))
                                    // 访问地址以及将http协议升级为ws协议
                                    .addLast(new WebSocketServerProtocolHandler("/ws"))

                                    // WebSocket处理器,把数据转化为可用对象
                                    .addLast(new TextWebSocketFrameHandler())
                                    // 业务处理器
                                    .addLast(new PBServerHandler());
                        }
                    });

            ChannelFuture future = serverBootstrap.bind(7000).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}
